import { Module } from 'vuex'
import { IRootState } from '../../type'
import { IHardwareState, IOtaUpload } from './types'

import {
  getPageList,
  newPageData,
  editPageData,
  otaUpload
} from '@/service/main/hardware/hardware'

const hardwareModule: Module<IHardwareState, IRootState> = {
  namespaced: true,
  state() {
    return {
      otaUploadList: []
    }
  },
  mutations: {
    changeotaUploadList(state, list: any) {
      state.otaUploadList = list
    }
  },
  getters: {
    pageListData(state) {
      return (pageName: string) => {
        const listData: any[] = (state as any)[`${pageName}List`] ?? []
        return listData
      }
    }
  },
  actions: {
    async getPageListDataAction({ commit }, pageName: string) {
      const pageUrl = `/backend/otaUploadList`
      console.log('pageNameeeeeeeeeeeee', pageUrl)
      if (pageUrl.length === 0) return
      const result: any = await getPageList(pageUrl)
      const list = result.data.data
      console.log('lllllllllllllllllist', list)
      commit('changeotaUploadList', list)
    },

    async otaUploadAction({ dispatch }, payload: IOtaUpload) {
      const pageUrl = `/backend/otaUpload`
      await otaUpload(pageUrl, { ...payload })
      dispatch('getPageListDataAction', { pageName: 'ota' })
    },

    async newPageDataAction({ dispatch }, payload: IOtaUpload) {
      const pageUrl = `/backend/newOtaUploadInfo`
      await newPageData(pageUrl, payload)

      dispatch('getPageListDataAction', {
        pageName: 'ota'
      })
    },

    async editPageDataAction({ dispatch }, payload: IOtaUpload) {
      if (!payload.id) return
      const pageUrl = `/backend/eitOtaUploadInfo`
      await editPageData(pageUrl, payload)

      dispatch('getPageListDataAction', {
        pageName: 'ota'
      })
    }
  }
}

export default hardwareModule
